package com.feidian.helper.ui;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.feidian.helper.R;
import com.feidian.helper.bean.Table;
import com.feidian.helper.bean.User;
import com.feidian.helper.net.NetManager;
import com.feidian.helper.util.Utils;

public class PersonalActivity extends Activity implements View.OnClickListener {

	private static final int DIALOG_CHG_NICKNAME = 10;
	private static final int DIALOG_CHG_EMAIL = 11;
	private static final int DIALOG_CHG_MOBILE = 12;

	private static final int SET_INFORMATION = 0X123;
	private static final int SET_INFORMAITON_FAILURE = 0X222;

	private static final int UPLOAD_SUCCESS = 0X124;
	private static final int UPLOAD_FAILURE = 0X125;

	private TextView tv_top_title;
	private ImageView mBack;
	private Dialog mDialog;
	private ImageView mCamera;
	private ImageView mHead;

	private TextView mNameTV;
	private EditText mQqET;
	private EditText mPhoneET;
	private Button mSaveBn;

	LinearLayout linearLayout;

	Uri uri;

	private static final int PHOTO_REQUEST_CAREMA = 1;// 拍照
	private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
	private static final int PHOTO_REQUEST_CUT = 3;// 结果

	private SharedPreferences sp;
	/* 头像名称 */
	private static String PHOTO_FILE_NAME = "temp_photo.jpg";
	private File tempFile;
	
	Dialog processDialog;

	String ImgUrl;// 头像服务器上的地址
	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case SET_INFORMATION: {
				Toast.makeText(PersonalActivity.this, "已经成功修改个人信息了",
						Toast.LENGTH_LONG).show();
				processDialog.dismiss();
				if (ImgUrl != null) {
					User.ImgUrl = ImgUrl.toString();
				}
				User.qq = mQqET.getText().toString();
				User.phone = mPhoneET.getText().toString();
				sp = getSharedPreferences(Table.CommentUserInf,
						Context.MODE_PRIVATE);
				Editor editor=sp.edit();
				editor.putString(Table.qq, User.qq);
				editor.putString(Table.phone, User.phone);
				editor.commit();
				Log.e("User.phone_Handler="+User.phone,">>>>>>>>>>");
				
				upData();
				finish();
			}
				break;
			case SET_INFORMAITON_FAILURE: {
				processDialog.dismiss();
				Toast.makeText(PersonalActivity.this, "修改错误", Toast.LENGTH_LONG)
						.show();
				processDialog.dismiss();
			}
				break;
			case UPLOAD_SUCCESS: {
				
				Log.e("(String)msg.obj.toString()="+(String)msg.obj.toString(),"................");
				
				
				String url = "http://115.29.103.105/User/SetInformation";
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				
				Log.e("stuId="+User.stuId,"............");
				Log.e("name="+User.name,"..............");
				Log.e("qq="+mQqET.getText().toString(),"..........");
				Log.e("phone="+mPhoneET.getText().toString(),".........");
				params.add(new BasicNameValuePair(Table.stuId, User.stuId));
				params.add(new BasicNameValuePair(Table.name, User.name));
				params.add(new BasicNameValuePair(Table.qq, mQqET.getText()
						.toString()));
				params.add(new BasicNameValuePair(Table.phone, mPhoneET
						.getText().toString()));
				//params.add(new BasicNameValuePair(Table.ImgUrl, ImgUrl));
				String te=(String)msg.obj.toString();
				if(te.length()>10){
					te=te.substring(1, te.length()-1);
					ImgUrl = "http://115.29.103.105"+te;
					params.add(new BasicNameValuePair(Table.ImgUrl, ImgUrl));
					Log.e("te.lenght()>10&&ImgUrl="+ImgUrl.toString(),"<<<<<<<<<<<<<<<<<");
				}
				else{
					params.add(new BasicNameValuePair(Table.ImgUrl, ImgUrl));
					Log.e("&&ImgUrl="+ImgUrl,"<<<<<<<<<<<<<<<<<");
				}
				
				
				InfThread infThread = new InfThread(url, params);
				infThread.start();

			}
				break;
			case UPLOAD_FAILURE: {
				// Toast.makeText(PersonalActivity.this,
				// "头像上传失败",Toast.LENGTH_LONG).show();
				processDialog.dismiss();
				Log.e("上传失败了", "....................");
			}
				break;
			default:
				break;
			}
		};
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_personal);
		sp = getSharedPreferences(Table.CommentUserInf, Context.MODE_PRIVATE);

		tv_top_title = (TextView) findViewById(R.id.title);
		tv_top_title.setText(getResources().getString(R.string.personal));
		mBack = (ImageView) findViewById(R.id.back);
		mBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		initView();
		
	}

	private void initView() {
		mCamera = (ImageView) findViewById(R.id.camera);
		mHead = (ImageView) findViewById(R.id.head);
		mNameTV = (TextView) findViewById(R.id.name_tv);
		mQqET = (EditText) findViewById(R.id.qq_et);
		mQqET.setOnClickListener(new  OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
			    mQqET.setCursorVisible(true);	
			}
		});
		mPhoneET = (EditText) findViewById(R.id.phone_et);
		mPhoneET.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				mPhoneET.setCursorVisible(true);
			}
		});
		mSaveBn = (Button) findViewById(R.id.save_bn);
		
		processDialog= new Dialog(PersonalActivity.this,
				R.style.NoTitleDialog);
		
		upData();

	}

	private void upData() {
		mCamera.setOnClickListener(this);
		if (User.head != null) {
			mHead.setImageBitmap(User.head);
		} else {
			SharedPreferences sp = getSharedPreferences(Table.CommentUserInf,
					Context.MODE_PRIVATE);
			if (!sp.getString(Table.headHeadImageName, "-1").equals("-1")) {
				tempFile = new File(Utils.getHelperFile(),sp.getString(Table.headHeadImageName, "-1"));
				Bitmap bitmap = BitmapFactory.decodeFile(tempFile.toString());
				if (bitmap != null) {
					User.head = bitmap;
					mHead.setImageBitmap(User.head);
				}
			}
		}
		if (User.name != null) {
			mNameTV.setText(User.name);
		} else {
			mNameTV.setText(sp.getString(Table.name, "错误"));
		}

		if (User.qq != null)
			mQqET.setText(User.qq.equals("null")?"无":User.qq);
		if (User.phone != null)
			mPhoneET.setText(User.phone.equals("null")?"无":User.phone);
		mSaveBn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (User.stuId == null || User.stuId.equals("")
						|| User.password == null || User.password.equals("")) {
					Toast.makeText(PersonalActivity.this, "用户尚未登录",
							Toast.LENGTH_LONG).show();
					return;
				}

				String url = "http://115.29.103.105/User/UploadImage";
				if (tempFile != null&&!tempFile.equals("-1")) {
					Log.e("tempFile="+tempFile.toString(),"<<<<<<<<<<<");
					UpLoadThread upLoadThread = new UpLoadThread(tempFile, url);
					upLoadThread.start();
				} else {
					//Log.e("tempFile=null or tempFile="+tempFile.toString(),"<<<<<<<<<<<<<<<");
					/*String tem=sp.getString(Table.headHeadImageName, "-1");
					if(tem!=null&&!tem.equals("")&&!tem.equals("null")&&!tem.equals("-1")){
						tempFile = new File(Utils.getHelperFile(),tem);
						UpLoadThread upLoadThread = new UpLoadThread(tempFile, url);
						upLoadThread.start();
						
						 * 正在保存Dialog
						 * 
						LayoutInflater inflater = LayoutInflater.from(PersonalActivity.this);
						View v = inflater.inflate(R.layout.dialogview, null);

						LinearLayout layout = (LinearLayout) v.findViewById(R.id.dialog_view);

						ImageView spaceshipImage = (ImageView) v.findViewById(R.id.img);
						Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(PersonalActivity.this,
								R.anim.animation);
						spaceshipImage.startAnimation(hyperspaceJumpAnimation);
						TextView textView=(TextView)v.findViewById(R.id.content);
						textView.setText("正在保存。。。。。");
						processDialog= new Dialog(PersonalActivity.this,
								R.style.NoTitleDialog);
						processDialog.setCancelable(true);
						processDialog.show();
						processDialog.setContentView(layout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
								LinearLayout.LayoutParams.MATCH_PARENT));
					}
					else
					{*/
						String url_no = "http://115.29.103.105/User/SetInformation";
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						
						Log.e("stuId="+User.stuId,"............");
						Log.e("name="+User.name,"..............");
						Log.e("qq="+mQqET.getText().toString(),"..........");
						Log.e("phone="+mPhoneET.getText().toString(),".........");
						params.add(new BasicNameValuePair(Table.stuId, User.stuId));
						params.add(new BasicNameValuePair(Table.name, User.name));
						params.add(new BasicNameValuePair(Table.qq, mQqET.getText()
								.toString()));
						params.add(new BasicNameValuePair(Table.phone, mPhoneET
								.getText().toString()));
						params.add(new BasicNameValuePair(Table.ImgUrl, User.ImgUrl));	
						Log.e("User.ImageUrl="+User.ImgUrl,"<,,,,,,,,,,,,,,,,,,");
						ImgUrl=User.ImgUrl;
						InfThread infThread = new InfThread(url_no, params);
						infThread.start();
						/*
						 * 正在保存Dialog
						 * */
						LayoutInflater inflater = LayoutInflater.from(PersonalActivity.this);
						View v = inflater.inflate(R.layout.dialogview, null);

						LinearLayout layout = (LinearLayout) v.findViewById(R.id.dialog_view);

						ImageView spaceshipImage = (ImageView) v.findViewById(R.id.img);
						Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(PersonalActivity.this,
								R.anim.animation);
						spaceshipImage.startAnimation(hyperspaceJumpAnimation);
						TextView textView=(TextView)v.findViewById(R.id.content);
						textView.setText("正在保存。。。。。");
						processDialog.setCancelable(true);
						processDialog.show();
						processDialog.setContentView(layout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
								LinearLayout.LayoutParams.MATCH_PARENT));
					//}
					    //Toast.makeText(PersonalActivity.this, "上传文件不能为空", Toast.LENGTH_LONG).show();
				}

				/*
				 * String url = "http://115.29.103.105/User/SetInformation";
				 * List<NameValuePair> params = new ArrayList<NameValuePair>();
				 * 
				 * params.add(new BasicNameValuePair(Table.stuId, User.stuId));
				 * params.add(new BasicNameValuePair(Table.name, User.name));
				 * params.add(new BasicNameValuePair(Table.qq, mQqET.getText()
				 * .toString())); params.add(new BasicNameValuePair(Table.phone,
				 * mPhoneET .getText().toString())); InfThread infThread = new
				 * InfThread(url, params); infThread.start();
				 */

			}
		});
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.camera:
			
			createDialogContentview();

			break;

		default:
			break;
		}

	}

	private void createDialogContentview() {
		if (User.stuId == null || User.stuId.equals("")
				|| User.password == null || User.password.equals("")) {
			Toast.makeText(PersonalActivity.this, "用户尚未登录", Toast.LENGTH_LONG)
					.show();
			return;
		}
		mDialog = new Dialog(PersonalActivity.this, R.style.dialog);
		LayoutInflater layoutInflater = this.getLayoutInflater();
		View view = layoutInflater.inflate(R.layout.chose_dialog, null, false);
		Button text1 = (Button)view.findViewById(R.id.chose_from_taking_picture);
		/*
		linearLayout = new LinearLayout(PersonalActivity.this);
		Button text1 = new Button(PersonalActivity.this);
		text1.setTextSize(30);
		text1.setBackgroundColor(getResources().getColor(R.color.white));
		text1.setText("从照相剪切获得");
		*/
		/*
		 * 从相机获取
		 */
		
		text1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				// TODO Auto-generated method stub
				// 激活相机
				// Intent intent = new
				// Intent("android.media.action.IMAGE_CAPTURE");
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				// 判断存储卡是否可以用，可用进行存储
				if (Utils.hasSdcard()) {
					Log.e("sd卡可用", ".........................");
					File f = new File(Environment.getExternalStorageDirectory()
							+ "/helper");
					if (!f.exists())
						f.mkdirs();
					PHOTO_FILE_NAME = System.currentTimeMillis() + ".jpg";
					tempFile = new File(f, PHOTO_FILE_NAME);
					// 从文件中创建uri
					Log.e("tempFile=" + tempFile.toString(), "...");
					uri = Uri.fromFile(tempFile);
					Log.e("uri=" + uri.toString(), "..");
					intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
				} else {
					Log.e("sd卡不可用", "..............................");
				}
				// 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
				startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
			}
		});
		
		/*
		TextView text2 = new TextView(PersonalActivity.this);
		text2.setBackgroundColor(getResources().getColor(R.color.bg_grey));
		text2.setHeight(1);
		Button text3 = new Button(PersonalActivity.this);
		text3.setText("从图库剪切获得");
		text3.setBackgroundColor(getResources().getColor(R.color.white));
		text3.setTextSize(30);
		*/
		Button text3 = (Button)view.findViewById(R.id.chose_from_picture);
		/*
		 * 从相册获取
		 */
		
		text3.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				// 激活系统图库，选择一张图片
				Intent intent = new Intent(Intent.ACTION_PICK);
				intent.setType("image/*");
				// 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
				startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
			}
		});
		
		/*
		ViewGroup.LayoutParams linearLayoutParam = new LayoutParams(
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);

		linearLayout.setOrientation(LinearLayout.VERTICAL);
		linearLayout.setBackgroundColor(getResources().getColor(R.color.white));
		linearLayout.setLayoutParams(linearLayoutParam);
		linearLayout.addView(text1, 0);
		linearLayout.addView(text2, 1);
		linearLayout.addView(text3, 2);
		*/
		mDialog.setContentView(view);
		mDialog.show();
	}

	/*
	 * 剪切图片
	 */
	private static final String IMAGE_FILE_LOCATION = "file://"
			+ Environment.getExternalStorageDirectory().getPath()
			+ File.separator + "helper/temp.jpg";// temp file
	Uri imageUri = Uri.parse(IMAGE_FILE_LOCATION);

	private void crop(Uri uri) {

		// 裁剪图片意图
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// 裁剪框的比例，1：1
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// 裁剪后输出图片的尺寸大小
		intent.putExtra("outputX", mHead.getWidth());
		intent.putExtra("outputY", mHead.getHeight());
		intent.putExtra("scale", true);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		intent.putExtra("outputFormat", "JPEG");// 图片格式
		intent.putExtra("noFaceDetection", true);// 取消人脸识别
		intent.putExtra("return-data", true);
		// 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
		startActivityForResult(intent, PHOTO_REQUEST_CUT);
	}

	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == PHOTO_REQUEST_GALLERY) {
			// 从相册返回的数据
			if (data != null) {
				// 得到图片的全路径
				Uri uri = data.getData();
				crop(uri);
			}

		} else if (requestCode == PHOTO_REQUEST_CAREMA) {
			// 从相机返回的数据
			if (Utils.hasSdcard()) {
				crop(Uri.fromFile(tempFile));
			} else {
				Toast.makeText(PersonalActivity.this, "未找到存储卡，无法存储照片！", 0)
						.show();
			}

		} else if (requestCode == PHOTO_REQUEST_CUT) {
			// 从剪切图片返回的数据
			if (data != null) {
				Bitmap bitmap = data.getParcelableExtra("data");
				if (Utils.hasSdcard()) {
					File f = Utils.getHelperFile();

					PHOTO_FILE_NAME = System.currentTimeMillis() + ".jpg";
					Log.e("PHOTO_FILE_NAME ="+PHOTO_FILE_NAME,".............");
					tempFile = new File(f, PHOTO_FILE_NAME);
					if (Utils.save(tempFile.toString(), bitmap)) {
						SharedPreferences sp = getSharedPreferences(
								Table.CommentUserInf, Context.MODE_PRIVATE);
						Editor editor = sp.edit();
						editor.putString(Table.headHeadImageName, PHOTO_FILE_NAME);
						editor.commit();
						User.head = bitmap;
						mDialog.dismiss();
						this.mHead.setImageBitmap(bitmap);
					} else {
						Log.e("头像为保存失败", ".................");
					}

				} else {
					Log.e("sd卡不可用", "..............................");
				}

			}
			try {
				// 将临时文件删除
				// tempFile.delete();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	class UpLoadThread extends Thread {
		private File mFile;
		private String mURL;

		public UpLoadThread(File file, String url) {
			// TODO Auto-generated constructor stub
			mFile = file;
			mURL = url;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			String upload = NetManager.getNetManager().uploadFile(mFile, mURL);
			Message msg = mHandler.obtainMessage();
			if (upload.equals("-1")) {

				msg.what = UPLOAD_FAILURE;
				mHandler.handleMessage(msg);
			} else {
				msg.what = UPLOAD_SUCCESS;
				msg.obj = upload;
				mHandler.sendMessage(msg);
			}

		}
	}

	class InfThread extends Thread {
		private String mUrl;
		private List<NameValuePair> mParams;

		public InfThread(String url, List<NameValuePair> params) {
			// TODO Auto-generated constructor stub
			mUrl = url;
			mParams = params;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			if(mUrl==null){
				Log.e("mUrl=null","<<<<<<<<<<<<<<");
			}
			if(mParams==null){
				Log.e("mParams=Null","<<<<<<<<<<<");
			}
			String context = NetManager.getNetManager().getWebWithPost(mUrl,
					mParams);
			if (context != null) {
				Log.e("contenxtontext_InfThread=", context);
			}

			else
				Log.e("context_InfThread=", "null");
			Message msg = mHandler.obtainMessage();
			if (context!=null&&!context.equals("-1")) {
				msg.what = SET_INFORMATION;
			} else {
				msg.what = SET_INFORMAITON_FAILURE;
			}
			mHandler.sendMessage(msg);
			super.run();
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		if (User.head != null) {
			mHead.setImageBitmap(User.head);
		}
		super.onResume();
	}

}
